package com.zz.common.tools.box.tools;

import org.apache.http.Header;

import android.util.Log;

import com.zz.common.tools.box.tools.BpClientUrlLoader.OnCompletedListener;
import com.zz.common.tools.box.tools.BpClientUrlLoader.OnErrorListener;

public class BpClientDataLoader extends BpFuture{
	public interface IBpOnDataLoaderCompleteListener {
		public void onComplete(int errCode, Object obj, Header[] headers, BpClientDataLoader loader);
	}
	
	public static final int DATA_LOADER_PARSE_ERROR = 1000;
	
	private static final String TAG = "BpDataLoader";
	private IBpOnDataLoaderCompleteListener mOnDataLoaderCompleteListener;
	private BpClientUrlLoader mUrlLoader;
	protected IBpDataLoaderParser mParser;
//	protected BpRunner mRunner;
	protected int mError = 0;
	

	public BpClientDataLoader(String url, IBpDataLoaderParser parser) {
		mParser = parser;
		mUrlLoader = new BpClientUrlLoader(url);
		mUrlLoader.setOnCompleteListener(new OnCompletedListener() {
			
			@Override
			public void onComplete(int respCode, Header[] headers, byte[] content,
					BpClientUrlLoader loader) {
				Object obj = null;
				if(respCode == 200)	{
					String str = new String(content);
					Log.i(TAG, str);
					if(null != mParser) {
						obj = mParser.parse(content);
						mError = mParser.getError();
					}
				} else {
					mError = respCode;
				}
				
				if(null != mOnDataLoaderCompleteListener){
					mOnDataLoaderCompleteListener.onComplete(mError, obj, headers, BpClientDataLoader.this);
				}
				
			}
		});
		
		mUrlLoader.setOnErrorListener(new OnErrorListener() {
			
			@Override
			public void onError(int errCode, BpClientUrlLoader loader) {
				mError = errCode;
				if(null != mOnDataLoaderCompleteListener) {
					mOnDataLoaderCompleteListener.onComplete(mError, null, null, BpClientDataLoader.this);
				}
			}
		});
		
	}
	
	public void setUserAgent(String userAgent) {
		
	}
	
	@Override
	public void run() {
		Log.i(TAG, "run------------");
		if(null != mUrlLoader){
			mUrlLoader.run();
		}
	}

	@Override
	public void cancel() {
		if(null != mUrlLoader){
			mUrlLoader.cancel();
			super.cancel();
		}
	}
	
	public void setBpOnDataLoaderCompleteListener(IBpOnDataLoaderCompleteListener listener)	{
		if(null != listener){
			mOnDataLoaderCompleteListener = listener;
		}
	}
}
